package servlets;

import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import database.DBHandler;
import database.DatabaseInterface;
/**
 * Servlet implementation class ViewThreadsProcessor
 */
//@WebServlet("/ViewThreadsProcessor")
public class ViewThreadsProcessor extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ViewThreadsProcessor() {
		super();
	}

	/**
	 * @see Servlet#init()
	 */
	public void init() throws ServletException {
		super.init();
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		super.destroy();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("view threads processor. doGet");
		// get session of the request
		HttpSession session = request.getSession();

		Boolean isLoggedIn = (Boolean) session.getAttribute("isLoggedIn");

		if (isLoggedIn == null || !(isLoggedIn.booleanValue())) {
			request.setAttribute("errorMsg", "Please Log In");
			String addr = "http://" + request.getServerName() + ":"
					+ request.getServerPort() + request.getContextPath();

			request.setAttribute("errorLink", addr);
			// get the request dispatcher
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/Error.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
			return;
		}

		// init the simulate DB
		DatabaseInterface db = DBHandler.getInstance();

		// get parameter do of the request
		String action = request.getParameter("do");

		// get the id of the request
		int id = -1;
		if (request.getParameter("id") != null)
			id = Integer.valueOf(request.getParameter("id"));

		if (action.equals("show")) {
			session.setAttribute("threadID", new Integer(id));
			// redirect to the book list servlet
			response.sendRedirect(request.getContextPath() + "/viewPosts");
			return;
		}

		// add thread
		if (action.equals("add")) {

			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/jsp/addThread.jsp");

			// forward to the jsp file to display the book list
			dispatcher.forward(request, response);
			return;

		}
		if (action.equals("delete")) {
			//session.setAttribute("username", "username0"); 
			Boolean isModerator = (Boolean) session.getAttribute("isModerator");
			Integer forumID = (Integer) session.getAttribute("forumID");
			Integer threadID = Integer.parseInt((String) request
					.getParameter("id"));
			String authorOfRemovedPost = request.getParameter("author");
			String username = (String) session.getAttribute("username");

			if (forumID == null || authorOfRemovedPost == null)
				return;

			// if username is author of thread or is moderator
			if (!authorOfRemovedPost.equalsIgnoreCase(username)
					&& (isModerator == null || !isModerator.booleanValue())) {
				request.setAttribute("errorMsg",
						"You do not have a suitable permittions to delete this thread this page");
				String addr = "http://" + request.getServerName() + ":"
						+ request.getServerPort() + request.getContextPath()
						+ "/viewThreads";

				request.setAttribute("errorLink", addr);
				// get the request dispatcher
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher("/jsp/Error.jsp");

				// forward to the jsp file to display the book list
				dispatcher.forward(request, response);
				return;
			}

			// delete the forum by id
			db.removeThread(threadID.intValue());

			// redirect to the book list servlet
			response.sendRedirect(request.getContextPath() + "/viewThreads");
			return;

		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// process add forum request
		System.out.println("view threads processor. doPost");
		HttpSession session = request.getSession();
		DatabaseInterface db = DBHandler.getInstance();

		String subject = request.getParameter("subject");
		String content = request.getParameter("content");
		String username = (String) session.getAttribute("username");
		Integer forumID = (Integer) session.getAttribute("forumID");

		Date tmp = GregorianCalendar.getInstance().getTime();
		SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH-mm-ss");
		String date = format.format(tmp); 
		db.addThread(username, forumID, subject, content, date);

		// redirect to the book list servlet
		response.sendRedirect(request.getContextPath() + "/viewThreads");
	}

}
